<?php

namespace App\Http\Controllers\Admins\Organization;

use App\Http\Controllers\Admins\BaseAdminController;
use App\Models\Admins;
use App\Models\Banner;
use App\Models\OperationalLogs;
use App\Models\Posts;
use Carbon\Carbon;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AccountController extends BaseAdminController
{
    /**
     * @param Request $request
     * @return array|Application|Factory|View
     */
    public function index(Request $request)
    {
        $condition = $request->get('condition','name');
        if($request->isMethod('post')){
            # 要执行的代码
//            $roles = array('center','is_super_user');
            $query = Admins::query()->latest();
            $keywords = $request->get('keywords',null);
            if ($keywords) {
                $query->where($condition, 'like', '%' . $keywords . '%');
            }
            $status = $request->get('status','all');
            if($status != 'all'){
                $query->where('status', $status);
            }
            $pageSize = $request->get('limit',10);
            # 计算offset值
            $offset = $request->get('offset',0);
            # 总数
            $total = $query->count();
            $data = $query->limit($pageSize)->offset($offset)->get();
            $result = array();
            if($data){
                foreach($data as $val){
                    $pids = null;
                    if($val['posts_id']) {
                        $pids = explode(',',$val['posts_id']);
                    }
                    $pname = null;
                    if($pids){
                        $pname = Posts::query()->whereIn('id',$pids)->get(['post_name','department_id'])->toArray();
                    }
                    $posts_name = '';
                    $department_name = '';
                    if($pname) {
                        foreach ($pname as $index){
                            $posts_name .= $index['post_name'].'<br>';
                            $departa_name = Banner::query()->where('id',$index['department_id'])->value('department_name');
                            $department_name  .= $departa_name.'<br>';;
                        }
//                        $posts_name =  array_reduce($pname, function ($result, $value) {
//                            return array_merge($result,array($value));
//                        }, array());
                        $posts_name = rtrim($posts_name,'<br>');
                        $department_name = rtrim($department_name,'<br>');
                    }
                    $status_show = '关闭';
                    if($val['status'] == 1){
                        $status_show = '开放';
                    }
                    $result[] = [
                        'id'=>$val['id'],
                        'name'=>$val['name'],
                        'username'=>$val['username'],
                        'phone'=>$val['phone'],
                        'posts_name'=>$posts_name,
                        'department_name'=>$department_name,
                        'status'=>$val['status'],
                        'status_show'=>$status_show,
                        'admin_name'=>Admins::query()->where('id',$val['add_admin_id'])->value('username')?:'-',
                        'crated_at'=>Carbon::parse($val['crated_at'])->toDateTimeString(),
                    ];
                }
            }
            return ret([
                'total'=>$total,
                'data'=>$result
            ]);
        }
        $admin_id = $this->admin_id;
        $subtitle = '账号管理';
        $opened_account_counts = Admins::query()->count();
        $total_account_counts = $opened_account_counts;
        $used_account_counts = Admins::query()->where('is_activation',1)->count();
        $compact = compact('subtitle','admin_id','total_account_counts','used_account_counts','opened_account_counts');
        return view('v1.admin.organization.account.index',$compact);
    }

    /**
     * 添加账号
     *
     * @param Request $request
     * @return Application|Factory|View|RedirectResponse
     */
    public function create(Request $request)
    {
        if($request->isMethod('post')) {
            $admin_id = $request->get('admin_id');
            $table = 'account';
            #表单验证
            $validator = AdminFormVerify($table, $request);
            if ($validator->fails()) {
                return $this->retError($validator,$request);
            }
            $post = $request->all();
            $vp = VerifyMobile($post['phone'],true);
            if($vp['code'] == 0){
                return $this->retError($vp['msg_zh'],$request);
            }
            $username = $request->get('username');
            $posts_id = implode(',',$post['posts_id']);
            unset($post['_token']);
            unset($post['posts_id']);
            $create = $post;
            $create['posts_id'] = $posts_id;
            $create['add_admin_id'] = $admin_id;
            $create['activation_code'] = ActivationCode();
            $create['password'] = bcrypt(123456);
            $logs = [
                'admin_id' => $admin_id,
                'operate_menu' => OperationalLogs::$operateItem['account_manage'],
                'operate_item' => $username,
                'operate_content' => '添加账号：' . $username,
            ];
            DB::beginTransaction();
            try {
                Admins::query()->create($create);
                #操作日志
                OperationalLogs::AddOperationalLogs($logs);
                DB::commit();
                return $this->retSuccess();
            } catch (\Exception $exception) {
                DB::rollback();
                return $this->retError($exception->getMessage(),$request);
            }
        }
        $url = route('v1.admin.organization.account.index');
        $params = [
            'url'=>$url,
            'success'=>'success'
        ];
        $subtitle = '新增账号';
        $view = 'v1.admin.organization.account.add';
        $posts = Posts::allData();
        $compact = compact('subtitle','params','posts');
        return view($view,$compact);
    }

    public function update(Request $request,$id)
    {
        $model = Admins::query();
        $where = [
            'id'=>$id
        ];
        $model_query = AdminModelQuery($id,$model,$where);
        if($model_query['code'] == 0){
            return  $this->retError($model_query['msg'],$request);
        }
        if($request->isMethod('post')) {
            $admin_id = $request->get('admin_id');
            $table = 'account';
            #表单验证
            $validator = AdminFormVerify($table, $request,'update');
            if ($validator->fails()) {
                return $this->retError($validator,$request);
            }
            $post = $request->all();
            $vp = VerifyMobile($post['phone'],true);
            if($vp['code'] == 0){
                return $this->retError($vp['msg_zh'],$request);
            }
            $username = $request->get('username');
            $where_unique_username = [
                'username'=>$username,
            ];
            $Model = Posts::query();
            $data_unique = AdminUpdateDataUniqueVerify($Model,$id,$where_unique_username);
            if($data_unique['code'] == 201){
                return $this->retError($data_unique['msg'],$request);
            }
            $where_unique_phone = [
                'phone'=>$post['phone'],
            ];
            $Model1 = Posts::query();
            $data_unique1 = AdminUpdateDataUniqueVerify($Model1,$id,$where_unique_phone);
            if($data_unique1['code'] == 201){
                return $this->retError($data_unique1['msg'],$request);
            }
            $posts_id = implode(',',$post['posts_id']);
            unset($post['_token']);
            unset($post['posts_id']);
            $update = $post;
            $update['posts_id'] = $posts_id;
            $update['add_admin_id'] = $admin_id;
            $logs = [
                'admin_id' => $admin_id,
                'operate_menu' => OperationalLogs::$operateItem['account_manage'],
                'operate_item' => $username,
                'operate_content' => '修改账号：' . $username,
            ];
            DB::beginTransaction();
            try {
                Admins::query()->where('id',$id)->create($update);
                #操作日志
                OperationalLogs::AddOperationalLogs($logs);
                DB::commit();
                return $this->retSuccess();
            } catch (\Exception $exception) {
                DB::rollback();
                return $this->retError($exception->getMessage(),$request);
            }
        }
        $url = route('v1.admin.organization.account.index');
        $params = [
            'url'=>$url,
            'success'=>'success'
        ];
        $subtitle = '修改账号';
        $view = 'v1.admin.organization.account.edit';
        $posts = Posts::allData();
        $columns = ['id','username','name','phone','posts_id'];
        $data = Admins::query()->where('id',$id)->first($columns);
        $data['posts_id'] = explode(',',$data['posts_id']);
        $compact = compact('subtitle','params','posts','data');
        return view($view,$compact);
    }
}
